<?php declare(strict_types=1);
/**
 * This file is part of Swoft.
 *
 * @link     https://swoft.org
 * @document https://swoft.org/docs
 * @contact  group@swoft.org
 * @license  https://github.com/swoft-cloud/swoft/blob/master/LICENSE
 */

namespace App\Console\Command;

use Swoft\Apollo\Config;
use Swoft\Bean\Annotation\Mapping\Inject;
use Swoft\Bean\BeanFactory;
use Swoft\Co;
use Swoft\Console\Annotation\Mapping\Command;
use Swoft\Console\Annotation\Mapping\CommandMapping;
use Swoft\Exception\SwoftException;
use Swoft\Http\Server\HttpServer;
use Swoft\Log\Helper\CLog;
use Swoft\WebSocket\Server\WebSocketServer;
use Throwable;

/**
 * Class AgentCommand
 *
 * @since 2.0
 *
 * @Command("agent", desc="this is an agent for Apllo config center")
 */
class AgentCommand
{
    /**
     * @Inject()
     *
     * @var Config
     */
    private $config;

    /**
     * @CommandMapping(name="index")
     */
    public function index()
    {
        $namespaces = [
            'application',
        ];
        $config = $this->config->newConfig();
        try {
            $config->listen($namespaces, [$this, 'updateSubNamespace']);
        } catch (Throwable $e) {
            CLog::error('Config agent fail(%s %s %d)!', $e->getMessage(), $e->getFile(), $e->getLine());
        }
    }



    /**
     * 获取需要监听的 namespace
     * @param array $data
     */
    public function updateSubNamespace (array $data)
    {
        foreach ($data as $namespace => $namespaceData) {
            $configKVs = $namespaceData['configurations'] ?? '';
            CLog::info('Application update success！');
            /** @var SubNamespaceListen $SubNamespaceListen */
            $SubNamespaceListen = BeanFactory::getBean("subNamespaceListen");
            $SubNamespaceListen->stop();
            if (! empty($configKVs)) {
                sgo(function () use ($configKVs, &$SubNamespaceListen){
                    $SubNamespaceListen->restart($configKVs);
                });
            }
        }
    }

}
